package com.example.petshopping.ui.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.petshopping.R;
import com.example.petshopping.model.AppAuthLoginRespVO;
import com.example.petshopping.model.AppMemberUserInfoRespVO;
import com.example.petshopping.model.CommonResult;
import com.example.petshopping.model.SmsCodeRequest;
import com.example.petshopping.model.SmsLoginRequest;
import com.example.petshopping.model.SmsSceneEnum;
import com.example.petshopping.network.RetrofitClient;
import com.example.petshopping.ui.main.MainActivity;
import com.example.petshopping.utils.TokenManager;
import com.example.petshopping.utils.UserInfoManager;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 手机号登录页面
 */
public class PhoneLoginActivity extends AppCompatActivity {

    private static final String TAG = "PhoneLoginActivity";
    private static final int COUNTDOWN_TIME = 60000; // 60秒倒计时
    private static final int COUNTDOWN_INTERVAL = 1000; // 1秒间隔

    private TextInputEditText etPhoneNumber;
    private TextInputEditText etVerificationCode;
    private MaterialButton btnGetCode;
    private MaterialButton btnConfirmLogin;
    private ProgressBar progressBar;
    private ImageButton btnBack;
    
    private CountDownTimer countDownTimer;
    private boolean isTimerRunning = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone_login);

        // 初始化控件
        initViews();
        
        // 设置点击事件
        setupClickListeners();
    }

    private void initViews() {
        etPhoneNumber = findViewById(R.id.etPhoneNumber);
        etVerificationCode = findViewById(R.id.etVerificationCode);
        btnGetCode = findViewById(R.id.btnGetCode);
        btnConfirmLogin = findViewById(R.id.btnConfirmLogin);
        progressBar = findViewById(R.id.progressBar);
        btnBack = findViewById(R.id.btnBack);
    }

    private void setupClickListeners() {
        // 返回按钮点击事件
        btnBack.setOnClickListener(v -> finish());

        // 获取验证码按钮点击事件
        btnGetCode.setOnClickListener(v -> {
            String phoneNumber = etPhoneNumber.getText().toString().trim();
            
            if (TextUtils.isEmpty(phoneNumber)) {
                Toast.makeText(PhoneLoginActivity.this, R.string.please_input_phone, Toast.LENGTH_SHORT).show();
                return;
            }
            
            if (phoneNumber.length() != 11) {
                Toast.makeText(PhoneLoginActivity.this, R.string.please_input_valid_phone, Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 模拟发送验证码
            simulateSendVerificationCode(phoneNumber);
        });

        // 登录按钮点击事件
        btnConfirmLogin.setOnClickListener(v -> {
            String phoneNumber = etPhoneNumber.getText().toString().trim();
            String verificationCode = etVerificationCode.getText().toString().trim();
            
            if (TextUtils.isEmpty(phoneNumber)) {
                Toast.makeText(PhoneLoginActivity.this, R.string.please_input_phone, Toast.LENGTH_SHORT).show();
                return;
            }
            
            if (phoneNumber.length() != 11) {
                Toast.makeText(PhoneLoginActivity.this, R.string.please_input_valid_phone, Toast.LENGTH_SHORT).show();
                return;
            }
            
            if (TextUtils.isEmpty(verificationCode)) {
                Toast.makeText(PhoneLoginActivity.this, R.string.please_input_verification_code, Toast.LENGTH_SHORT).show();
                return;
            }
            
            if (verificationCode.length() != 4) {
                Toast.makeText(PhoneLoginActivity.this, R.string.verification_code_format_error, Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 模拟验证登录
            simulateLogin(phoneNumber, verificationCode);
        });
    }

    /**
     * 发送验证码
     */
    private void simulateSendVerificationCode(String phoneNumber) {
        if (isTimerRunning) {
            return;
        }
        // 显示加载中
        showLoading(true);
        // 构建请求对象，使用会员登录场景
        SmsCodeRequest request = new SmsCodeRequest(phoneNumber, SmsSceneEnum.MEMBER_LOGIN);
        // 发送网络请求
        RetrofitClient.getInstance().getApiService().sendSmsCode(request)
                .enqueue(new Callback<CommonResult<Boolean>>() {
                    @Override
                    public void onResponse(Call<CommonResult<Boolean>> call, Response<CommonResult<Boolean>> response) {
                        // 隐藏加载中
                        showLoading(false);
                        
                        if (response.isSuccessful() && response.body() != null) {
                            CommonResult<Boolean> result = response.body();
                            if (result.isSuccess()) {
                                // 显示提示
                                Toast.makeText(PhoneLoginActivity.this, R.string.verification_code_sent, Toast.LENGTH_SHORT).show();
                                // 启动倒计时
                                startCountDown();
                            } else {
                                // 显示错误信息
                                Toast.makeText(PhoneLoginActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            // 网络请求失败
                            Toast.makeText(PhoneLoginActivity.this, R.string.network_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                    
                    @Override
                    public void onFailure(Call<CommonResult<Boolean>> call, Throwable t) {
                        // 隐藏加载中
                        showLoading(false);
                        
                        // 显示错误信息
                        Toast.makeText(PhoneLoginActivity.this, R.string.network_error, Toast.LENGTH_SHORT).show();
                        Log.e(TAG, "发送验证码失败", t);
                    }
                });
    }

    /**
     * 开始倒计时
     */
    private void startCountDown() {
        btnGetCode.setEnabled(false);
        isTimerRunning = true;
        
        countDownTimer = new CountDownTimer(COUNTDOWN_TIME, COUNTDOWN_INTERVAL) {
            @Override
            public void onTick(long millisUntilFinished) {
                btnGetCode.setText(String.format(getString(R.string.seconds_to_retry), millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                btnGetCode.setText(R.string.get_verification_code);
                btnGetCode.setEnabled(true);
                isTimerRunning = false;
            }
        }.start();
    }

    /**
     * 登录
     */
    private void simulateLogin(String phoneNumber, String verificationCode) {
        // 显示加载中
        showLoading(true);
        
        // 构建请求对象
        SmsLoginRequest request = new SmsLoginRequest(phoneNumber, verificationCode);
        
        // 发送登录请求
        RetrofitClient.getInstance().getApiService().smsLogin(request, "31")
                .enqueue(new Callback<CommonResult<AppAuthLoginRespVO>>() {
                    @Override
                    public void onResponse(Call<CommonResult<AppAuthLoginRespVO>> call, Response<CommonResult<AppAuthLoginRespVO>> response) {
                        // 隐藏加载中
                        showLoading(false);
                        
                        if (response.isSuccessful() && response.body() != null) {
                            CommonResult<AppAuthLoginRespVO> result = response.body();
                            if (result.isSuccess() && result.getData() != null) {
                                // 登录成功
                                AppAuthLoginRespVO data = result.getData();
                                
                                // 保存登录状态
                                TokenManager.saveToken(PhoneLoginActivity.this, data.getAccessToken());
                                TokenManager.saveRefreshToken(PhoneLoginActivity.this, data.getRefreshToken());
                                TokenManager.saveUserId(PhoneLoginActivity.this, data.getUserId());
                                
                                // 获取用户基本信息
                                getUserInfo(data.getAccessToken());
                            } else {
                                // 登录失败，显示错误信息
                                Toast.makeText(PhoneLoginActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            // 网络请求失败
                            Toast.makeText(PhoneLoginActivity.this, R.string.network_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                    
                    @Override
                    public void onFailure(Call<CommonResult<AppAuthLoginRespVO>> call, Throwable t) {
                        // 隐藏加载中
                        showLoading(false);
                        
                        // 显示错误信息
                        Toast.makeText(PhoneLoginActivity.this, R.string.network_error, Toast.LENGTH_SHORT).show();
                        Log.e(TAG, "登录失败", t);
                    }
                });
    }

    /**
     * 显示或隐藏加载进度
     */
    private void showLoading(boolean show) {
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        btnConfirmLogin.setEnabled(!show);
        if (!isTimerRunning) {
            btnGetCode.setEnabled(!show);
        }
    }

    /**
     * 获取用户基本信息
     */
    private void getUserInfo(String accessToken) {
        // 发送获取用户信息请求（Authorization头已由拦截器自动添加）
        RetrofitClient.getInstance().getApiService().getUserInfo()
                .enqueue(new Callback<CommonResult<AppMemberUserInfoRespVO>>() {
                    @Override
                    public void onResponse(Call<CommonResult<AppMemberUserInfoRespVO>> call, Response<CommonResult<AppMemberUserInfoRespVO>> response) {
                        // 隐藏加载中
                        showLoading(false);
                        
                        if (response.isSuccessful() && response.body() != null) {
                            CommonResult<AppMemberUserInfoRespVO> result = response.body();
                            if (result.isSuccess() && result.getData() != null) {
                                // 保存用户信息
                                UserInfoManager.saveUserInfo(PhoneLoginActivity.this, result.getData());
                                
                                // 显示登录成功提示
                                Toast.makeText(PhoneLoginActivity.this, R.string.login_success, Toast.LENGTH_SHORT).show();
                                
                                // 跳转到主页
                                startMainActivity();
                            } else {
                                // 获取用户信息失败，但登录成功了，依然跳转
                                Log.w(TAG, "获取用户信息失败: " + result.getMsg());
                                Toast.makeText(PhoneLoginActivity.this, R.string.login_success, Toast.LENGTH_SHORT).show();
                                startMainActivity();
                            }
                        } else {
                            // 网络请求失败，但登录成功了，依然跳转
                            Log.w(TAG, "获取用户信息网络请求失败");
                            Toast.makeText(PhoneLoginActivity.this, R.string.login_success, Toast.LENGTH_SHORT).show();
                            startMainActivity();
                        }
                    }
                    
                    @Override
                    public void onFailure(Call<CommonResult<AppMemberUserInfoRespVO>> call, Throwable t) {
                        // 隐藏加载中
                        showLoading(false);
                        
                        // 获取用户信息失败，但登录成功了，依然跳转
                        Log.e(TAG, "获取用户信息失败", t);
                        Toast.makeText(PhoneLoginActivity.this, R.string.login_success, Toast.LENGTH_SHORT).show();
                        startMainActivity();
                    }
                });
    }

    /**
     * 跳转到主页
     */
    private void startMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        overridePendingTransition(0,0);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消倒计时
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }
} 